import image from '@/assets/6.jpg';
import useAuthStore from '@/store/authStore';
import { Avatar } from 'antd';
import axios from 'axios';
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import ShortUniqueId from 'short-unique-id';
import './ModelCard.scss';

const uid = new ShortUniqueId();

export function getNodeId(nodeType: string) {
  return nodeType + "-" + uid.randomUUID(5);
}

interface ModelCardProps {
  app: {
    title: string;
    category: string;
    description: string;
    detailLink: string;
    apiLink: string;
    trialLink: string;
  };
}

const ModelCard: React.FC<ModelCardProps> = ({ app }) => {
  const navigate = useNavigate();
  const { accessToken } = useAuthStore(); 
  const [folderId, setFolderId] = useState<string | null>(null);

  const handleNavigation = (path: string) => {
    navigate(path);
  };

  const handleTrialClick = async () => {
    try {
      const headers = {
        'Authorization': `Bearer ${accessToken}`,
        'Cache-Control': 'no-cache',
        'Accept': '*/*',
      };

      console.log('Starting API calls with access token:', accessToken);

      const [whoamiResponse, foldersResponse, variablesResponse, flowsResponse, storeCheckResponse, apiKeyCheckResponse] = await Promise.all([
        axios.get('http://localhost:3000/api/v1/users/whoami', { headers }),
        axios.get('http://localhost:7860/api/v1/folders/', { headers }),
        axios.get('http://localhost:7860/api/v1/variables/', { headers }),
        axios.get('http://localhost:7860/api/v1/flows/', { headers }),
        axios.get('http://localhost:7860/api/v1/store/check/', { headers }),
        axios.get('http://localhost:7860/api/v1/store/check/api_key', { headers }),
      ]);

      console.log('whoami response:', whoamiResponse.data);
      console.log('folders response:', foldersResponse.data);
      console.log('variables response:', variablesResponse.data);
      console.log('flows response:', flowsResponse.data);
      console.log('store check response:', storeCheckResponse.data);
      console.log('API key check response:', apiKeyCheckResponse.data);

      if (foldersResponse.data.length > 0) {
        const firstFolderId = foldersResponse.data[0].id;
        setFolderId(firstFolderId);
        console.log('First folder ID:', firstFolderId);

        const randomId = getNodeId('TongyiQwenChatModel');
        console.log('Generated Random ID:', randomId);

        // 使用获取到的 folderId 做进一步操作
        const requestBody = {
          name: "通义千问应用模板",
          data: {
            nodes: [
              {
                id: randomId,
                type: "genericNode",
                position: {
                  x: 201,
                  y: 114.02499771118164
                },
                data: {
                  type: "TongyiQwenChatModel",
                  node: {
                    template: {
                      "_type": "Component",
                      "code": {
                        "type": "code",
                        "required": true,
                        "placeholder": "",
                        "list": false,
                        "show": true,
                        "multiline": true,
                        "value": "from langchain_community.chat_models.tongyi import ChatTongyi\nfrom pydantic.v1 import SecretStr\n\nfrom langflow.base.constants import STREAM_INFO_TEXT\nfrom langflow.base.models.model import LCModelComponent\nfrom langflow.field_typing.constants import LanguageModel\nfrom langflow.io import BoolInput, DropdownInput, FloatInput, MessageTextInput, SecretStrInput\nfrom langflow.template.field.base import Output\n\nclass TongyiQwenComponent(LCModelComponent):\n    display_name: str = \"通义千问\"\n    description: str = \"使用通义千问大模型生成文本\"\n    documentation: str = \"https://python.langchain.com/docs/integrations/chat/tongyi\"\n    icon = \"TongyiQwen\"\n    name = \"TongyiQwenChatModel\"\n    outputs = [\n        Output(display_name=\"文本\", name=\"text_output\", method=\"text_response\"),\n        Output(display_name=\"语言模型\", name=\"model_output\", method=\"build_model\"),\n    ]\n    inputs = [\n        MessageTextInput(\n            name=\"input_value\",\n            display_name=\"输入\",\n        ),\n        DropdownInput(\n            name=\"model\",\n            display_name=\"模型名称\",\n            options=[\n                \"qwen-turbo\",\n                \"qwen-turbo-0624\",\n                \"qwen-plus\",\n                \"qwen-plus-0624\",\n                \"qwen-max\",\n                \"qwen-max-0428\",\n                \"qwen-max-longcontext\",\n            ],\n            info=\"https://help.aliyun.com/zh/dashscope/developer-reference/model-introduction\",\n            value=\"qwen-turbo\",\n        ),\n        SecretStrInput(\n            name=\"tongyi_api_key\",\n            display_name=\"通义千问API Key\",\n            info=\"可以从 https://help.aliyun.com/zh/dashscope/developer-reference/acquisition-and-configuration-of-api-key 获取\",\n        ),\n        FloatInput(\n            name=\"top_p\",\n            display_name=\"Top p\",\n            value=0.8,\n            advanced=True,\n        ),\n        FloatInput(\n            name=\"temperature\",\n            display_name=\"温度\",\n            value=0.95,\n        ),\n        BoolInput(\n            name=\"stream\",\n            display_name=\"流式输出\",\n            info=STREAM_INFO_TEXT,\n            advanced=True,\n        ),\n        MessageTextInput(\n            name=\"system_message\",\n            display_name=\"系统提示词\",\n            info=\"传递给模型的提示词\",\n            advanced=True,\n        ),\n    ]\n\n    def build_model(self) -> LanguageModel:  # type: ignore[type-var]\n        model = self.model\n        tongyi_api_key = self.tongyi_api_key\n        top_p = self.top_p\n        temperature = self.temperature\n\n        try:\n            output = ChatTongyi(  # type: ignore\n                model=model,\n                api_key=SecretStr(tongyi_api_key),\n                top_p=top_p,\n                temperature=temperature,\n            )\n        except Exception as e:\n            raise ValueError(\"无法连接到通义千问 API\") from e\n\n        return output  # type: ignore\n",
                      fileTypes: [],
                      file_path: "",
                      password: false,
                      name: "code",
                      advanced: true,
                      dynamic: true,
                      info: "",
                      load_from_db: false,
                      title_case: false
                    },
                    input_value: {
                      trace_as_input: true,
                      trace_as_metadata: true,
                      load_from_db: false,
                      list: false,
                      required: false,
                      placeholder: "",
                      show: true,
                      value: "",
                      name: "input_value",
                      display_name: "输入",
                      advanced: false,
                      input_types: [
                        "Message"
                      ],
                      dynamic: false,
                      info: "",
                      title_case: false,
                      type: "str"
                    },
                    model: {
                      trace_as_metadata: true,
                      options: [
                        "qwen-turbo",
                        "qwen-turbo-0624",
                        "qwen-plus",
                        "qwen-plus-0624",
                        "qwen-max",
                        "qwen-max-0428",
                        "qwen-max-longcontext"
                      ],
                      required: false,
                      placeholder: "",
                      show: true,
                      value: "qwen-turbo",
                      name: "model",
                      display_name: "模型名称",
                      advanced: false,
                      dynamic: false,
                      info: "https://help.aliyun.com/zh/dashscope/developer-reference/model-introduction",
                      title_case: false,
                      type: "str"
                    },
                    stream: {
                      trace_as_metadata: true,
                      list: false,
                      required: false,
                      placeholder: "",
                      show: true,
                      value: false,
                      name: "stream",
                      display_name: "流式输出",
                      advanced: true,
                      dynamic: false,
                      info: "以流的形式连续输出模型生成的内容",
                      title_case: false,
                      type: "bool"
                    },
                    system_message: {
                      trace_as_input: true,
                      trace_as_metadata: true,
                      load_from_db: false,
                      list: false,
                      required: false,
                      placeholder: "",
                      show: true,
                      value: "",
                      name: "system_message",
                      display_name: "系统提示词",
                      advanced: true,
                      input_types: [
                        "Message"
                      ],
                      dynamic: false,
                      info: "传递给模型的提示词",
                      title_case: false,
                      type: "str"
                    },
                    temperature: {
                      trace_as_metadata: true,
                      list: false,
                      required: false,
                      placeholder: "",
                      show: true,
                      value: 0.95,
                      name: "temperature",
                      display_name: "温度",
                      advanced: false,
                      dynamic: false,
                      info: "",
                      title_case: false,
                      type: "float"
                    },
                    tongyi_api_key: {
                      load_from_db: false,
                      required: false,
                      placeholder: "",
                      show: true,
                      value: "",
                      name: "tongyi_api_key",
                      display_name: "通义千问API Key",
                      advanced: false,
                      input_types: [],
                      dynamic: false,
                      info: "可以从 https://help.aliyun.com/zh/dashscope/developer-reference/acquisition-and-configuration-of-api-key 获取",
                      title_case: false,
                      password: true,
                      type: "str"
                    },
                    top_p: {
                      trace_as_metadata: true,
                      list: false,
                      required: false,
                      placeholder: "",
                      show: true,
                      value: 0.8,
                      name: "top_p",
                      display_name: "Top p",
                      advanced: true,
                      dynamic: false,
                      info: "",
                      title_case: false,
                      type: "float"
                    }
                  },
                  description: "使用通义千问大模型生成文本",
                  icon: "TongyiQwen",
                  base_classes: [
                    "LanguageModel",
                    "Message"
                  ],
                  display_name: "通义千问",
                  documentation: "https://python.langchain.com/docs/integrations/chat/tongyi",
                  custom_fields: {},
                  output_types: [],
                  pinned: false,
                  conditional_paths: [],
                  frozen: false,
                  outputs: [
                    {
                      types: [
                        "Message"
                      ],
                      selected: "Message",
                      name: "text_output",
                      display_name: "文本",
                      method: "text_response",
                      value: "__UNDEFINED__",
                      cache: true
                    },
                    {
                      types: [
                        "LanguageModel"
                      ],
                      selected: "LanguageModel",
                      name: "model_output",
                      display_name: "语言模型",
                      method: "build_model",
                      value: "__UNDEFINED__",
                      cache: true
                    }
                  ],
                  field_order: [
                    "input_value",
                    "model",
                    "tongyi_api_key",
                    "top_p",
                    "temperature",
                    "stream",
                    "system_message"
                  ],
                  beta: false,
                  edited: false
                },
                id: randomId
              },
          }],
            edges: [],
            viewport: {
              x: 0,
              y: 0,
              zoom: 1
            }
          },
          description: "智链iLink 点亮智慧 链接未来",
          folder_id: firstFolderId
        };

        const response = await axios.post(
          'http://localhost:3000/api/v1/flows/',
          requestBody,
          {
            headers: {
              'Authorization': `Bearer ${accessToken}`,
              'Accept': '*/*',
              'Cache-Control': 'no-cache',
              'Connection': 'keep-alive',
            }
          }
        );

        console.log('Trial response:', response.data);
         // 获取响应数据中的id
         const flowId = response.data.id;
         console.log('Created Flow ID:', flowId);
 
         // 跳转到新创建的flow页面
         // 处理试用的成功响应
         alert('试用成功！');
         window.location.href = `http://localhost:3000/flow/${flowId}`;
       } else {
         console.error('No folders found.');
         alert('没有找到合适的文件夹，请稍后再试。');
       }
     } catch (error) {
       console.error('Error starting trial:', error);
       alert('试用失败，请稍后再试。');
     }
   };

  return (
    <div className="model-card" style={{ width: '31.25rem', height: '15rem', marginBottom:'0.25rem'}}>
      <div className="model-card-header">
        <Avatar src={image} alt={app.title} size={64} className="model-card-image" />
        <div className="model-card-title-category">
          <h2 className="model-card-title">{app.title}</h2>
          <span className="model-card-category">{app.category}</span>
        </div>
      </div>
      <div className="model-card-content">
        <p className="model-card-description">{app.description}</p>
      </div>
      <div className="model-card-actions">
        <a onClick={() => handleNavigation('/moxing/xiangqing')} className="model-card-button">
          查看详情
        </a>
        <a href={app.apiLink} className="model-card-button">
          API调用示例
        </a>
        <a onClick={handleTrialClick} className="model-card-button">
          立即体验
        </a>
      </div>
      {folderId && <p>Folder ID: {folderId}</p>} {/* 显示获取到的 folder ID */}
    </div>
  );
};

export default ModelCard;
